import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';

import '../../resources/kq_theme_colors.dart';

class ChartPieModel {
  ///画布高度
  double sizeHeight;

  ///画布宽度
  double sizeWitdh;

  ///外弧半径，默认为画布高宽的最小值的一半
  double outRadius;

  ///内弧半径,默认30
  double innerRadius;

  ///无数据时候的颜色,默认为999999
  Color noColor;

  ///空白间隔所占比例默认为0.4%
  double blankProportion;

  ///空白间隔的颜色默认为白色
  Color spcColor;

  ///扇形数据
  List<ChartPieValue> chartModel;

  ChartPieModel(
      {required this.sizeHeight,
      required this.sizeWitdh,
      this.outRadius = 0,
      this.innerRadius = 0,
      this.blankProportion = 0.004,
      this.spcColor = KqThemeColors.bgWhite,
      this.noColor = KqThemeColors.text999,
      required this.chartModel});

  void _initData() {
    innerRadius = innerRadius == 0 ? 80.r : innerRadius;
    if (outRadius == 0) {
      outRadius = sizeHeight > sizeWitdh ? sizeWitdh / 2 : sizeHeight / 2;
    }
  }

  ///计算每块扇形区域的占比
  void calculateEvenProportion(List<ChartPieValue> list) {
    _initData();
    if (list.length > 1) {
      double sum = 0; //总数
      for (var element in list) {
        sum = sum + double.parse(element.value);
      }
      double endAngle = 0;
      List<ChartPieValue> noPieList = [];
      for (int i = 0; i < list.length; i++) {
        ChartPieValue pie = list[i];
        if (i == list.length - 1) {
          pie.startAngle = endAngle;
          pie.proportion = 1 - endAngle - blankProportion;
          endAngle = pie.proportion + pie.startAngle;
          ChartPieValue noPie = ChartPieValue(value: '0', color: spcColor);
          noPie.startAngle = endAngle;
          noPie.proportion = blankProportion;
          noPieList.add(noPie);
        } else {
          pie.startAngle = endAngle;
          pie.proportion = double.parse(pie.value) / sum - blankProportion;
          endAngle = pie.proportion + pie.startAngle;
          ChartPieValue noPie = ChartPieValue(value: '0', color: spcColor);
          noPie.startAngle = endAngle;
          noPie.proportion = blankProportion;
          noPieList.add(noPie);
          endAngle = endAngle + blankProportion;
        }
      }
      List<ChartPieValue> newPieList = [];
      for (int i = 0; i < list.length; i++) {
        ChartPieValue pie = list[i];
        ChartPieValue noPie = noPieList[i];
        newPieList.add(pie);
        newPieList.add(noPie);
      }
      chartModel = newPieList;
    } else if (list.isNotEmpty) {
      ChartPieValue pie = list.first;
      pie.proportion = 1;
      chartModel = list;
    } else {
      ChartPieValue pie = ChartPieValue(value: '100', color: noColor);
      pie.proportion = 1;
      chartModel = [pie];
    }
  }
}

class ChartPieValue {
  ///内如数据
  String value;

  ///扇形区域颜色
  Color color;

  ///扇形占比，无需传入自行计算
  double proportion = 0;

  ///起始位置
  double startAngle = 0;

  ChartPieValue({required this.value, required this.color});
}
